from django.shortcuts import render,redirect,reverse
from django.http.response import JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods,require_POST,require_GET
from .models import Blog,BlogComment,BlogCategory
from .forms import PubForm
from .models import Blog
from django.db.models import Q


# Create your views here.

## 首页
def index(request):
    blogs = Blog.objects.all()
    return render(request,"index.html",context={"blogs":blogs})

## 详情页
def blog_details(request,blog_id):
    # 获取 blog
    try:
        blog = Blog.objects.get(id=blog_id)
    except Exception as e:
        blog = None
    return render(request,"blog_details.html",context={"blog":blog})

## 发布博客
@require_http_methods(['GET','POST'])
@login_required()
def blog_pub(request):
    if request.method == "GET":
        ## 获取到分类 显示
        categories = BlogCategory.objects.all()
        return render(request,"pub_blog.html",context={"categories":categories})
    else:
        form = PubForm(request.POST)
        print("=================")
        print(form)
        if form.is_valid():
            ## 拿出数据
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            category_id = form.cleaned_data.get('category')
            ## 生成对象 author = request.user 将当前登录的用户设置为 博客文章和的作者
            blog = Blog.objects.create(title=title,content=content,category_id=category_id,author=request.user)
            print(f"当前登录用户是：{request.user.username}")
            #return JsonResponse({"code":200,"message":"博客发布成功","data":{"blog_id":blog.id,"title":title,"content":content,"category_id":category_id,"author":request.user}})
            return JsonResponse({"code":200,"message":"博客发布成功","data":{"blog_id":blog.id}})
        else:
            return JsonResponse({"code":"400","message":"参数错误"})

##评论功能
@require_POST
def blogComment(request):
    ## 获取 blog_id、content
    blog_id = request.POST.get("blog_id")
    content = request.POST.get("content")
    BlogComment.objects.create(content=content,blog_id=blog_id,author=request.user)
    ## 重新加载详情页
    ## 在函数中传递参数 kwargs 代表关键字参数 kwargs 传递给 reverse blog_id=1 会使 URL 变成 /blog/1/
    return redirect(reverse("blog:blog_details",kwargs={"blog_id":blog_id})) ## 注意参数的位置



### serach
@require_GET
def blog_search(request):
    ## 访问的路径时 /search?query=xxx
    query = request.GET.get("query")
    blogs = Blog.objects.filter(Q(title__icontains=query)|Q(content__icontains=query)).all()
    return render(request,'index.html',{"blogs":blogs})


